<?php

global $wpdb,$post;
$count = $wpdb->get_var("
	SELECT COUNT(meta_value) FROM $wpdb->commentmeta
	LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
	WHERE meta_key = 'rating'
	AND comment_post_ID = $post->ID
	AND comment_approved = '1'
	AND meta_value > 0
");

$rating = $wpdb->get_var("
	SELECT SUM(meta_value) FROM $wpdb->commentmeta
	LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
	WHERE meta_key = 'rating'
	AND comment_post_ID = $post->ID
	AND comment_approved = '1'
");

if($count > 0) :

		$average = number_format($rating / $count, 0);

		echo '<div class="rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';
		
		echo '<span itemprop="ratingValue" class="ratingvalue">'.$average.'</span>';
					
		echo write_rating_stars($average);
		
		echo '</div>';

endif;

return $count;